package org.mms.exception;

import org.mms.pojo.util.ResponseMessage;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.http.HttpStatus;

@RestControllerAdvice
public class GlobalExceptionHandler {

    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ExceptionHandler(BusinessException.class)
    @ResponseBody
    public ResponseMessage<?> handleBusinessException(Exception e,
                                                     HttpServletRequest request,
                                                     HttpServletResponse response) {

        logger.warn("an business exception occurred: \n\t{}", e.toString());

        response.setStatus(HttpStatus.BAD_REQUEST.value());
        return ResponseMessage.error(HttpStatus.BAD_REQUEST.value(), e.getMessage());
    }

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public ResponseMessage<?> handleException(Exception e,
                                             HttpServletRequest request,
                                             HttpServletResponse response) {

        logger.error("an system exception occurred: \n\t{}", e.toString());

        response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
        return ResponseMessage.error(HttpStatus.INTERNAL_SERVER_ERROR.value(), e.getMessage());
    }
}